<template>
	<el-upload class="btn-upload" 
		:style="{width: width, height: height, lineHeight: height}"
		:accept="formats.map(e => '.' + e).join(',')" 
		:action="$util.baseUrl + uploadUrl"
		:headers="headers" 
		:show-file-list="false" 
		:before-upload="beforeUpload" 
		:on-success="onUploaded">

		<el-image v-if="imageUrl" :src="imageUrl" class="image" fit="cover"></el-image>
		<i v-else class="el-icon-plus"></i>

	</el-upload>
</template>

<script>
	export default {
		props: {
			imageUrl: String,
			uploadUrl: String,
			type: String,
			width: {
				type: String,
				default: '100%'
			},
			height: {
				type: String,
				default: 'auto'
			}
		},
		data() {
			return {
				formats: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif']
			}
		},
		computed: {
			headers() {
				return {
					token: this.$store.getters.token,
					type: this.type
				}
			}
		},
		methods: {
			beforeUpload(file) {
				const format = file.type.split('/')[1];
				if (!this.formats.includes(format)) return this.$util.msg(`图片仅支持${this.formats.join('/')}格式`);
				if (file.size / 1024 / 1024 > 2) return this.$util.msg('图片大小不能超过2MB');

				this.uploading = this.$loading({
					text: '上传中...',
					body: true
				});
				return true;
			},
			onUploaded(res) {
				this.uploading.close();

				if (res.state == 'ok') {
					this.$emit('update:imageUrl', res.url);
				} else {
					this.$util.msg(res.msg);
				}
			}
		}
	}
</script>

<style lang="scss">
	.btn-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		display: flex;
		margin-bottom: 15px;
		
		&:hover {
			border-color: $color-primary;
		}
		
		.el-upload {
			flex: 1;
			
			.el-icon-plus {
				font-size: 28px;
				color: #8c939d;
				text-align: center;
				line-height: 2;
			}
		}
		
		.image {
			width: 100%;
			height: 100%;
		}
	}
</style>
